package com.mishow.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.android.volley.Request;
import com.mishow.R;
import com.mishow.activity.HotAnnunciateActivity;
import com.mishow.activity.LoginActivity;
import com.mishow.activity.MainActivity;
import com.mishow.activity.SearchActivity;
import com.mishow.activity.SearchNearbyActivity;
import com.mishow.activity.StarFactoryActivity;
import com.mishow.adapter.ActivitiesListViewAdapter;
import com.mishow.adapter.PersonGridAdapter;
import com.mishow.adapter.ProcureGridAdapter;
import com.mishow.bean.HomeBanner;
import com.mishow.bean.HomeShortcutMenu;
import com.mishow.bean.HomeStarShow;
import com.mishow.fragment.base.BaseFragment;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.refresh.PullPushRefreshLayout;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.HomePageDataResponse;
import com.mishow.request.response.HomePageDataResponse.Result;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.Constants;
import com.mishow.utils.DeviceUtil;
import com.mishow.utils.ToastUtil;
import com.mishow.utils.UmengAnalyticUtil;
import com.mishow.volley.http.request.FastJsonRequest;
import com.mishow.widget.CirculatoryViewPager;
import com.mishow.widget.CirculatoryViewPager.PageClickListenner;
import com.mishow.widget.MyGridView;
import com.mishow.widget.MyListView;
import com.mishow.widget.ObservableScrollView;
import com.mishow.zxing.activity.CaptureActivity;
/**
 * 
 * 作者：wei.miao<br/>
 * 描述：首页Fragment
 */
public class IndexFragment extends BaseFragment implements OnClickListener,OnRefreshListener{
	/** Fragment布局 **/
	private View mView;
	/** activity对象 **/
	private Activity mActivity;
	
	private PullPushRefreshLayout swipe_ly;
	
	private ObservableScrollView sv_procure;
	/** 搜附近-超星榜-热通告-星工厂 适配器 **/
	private ProcureGridAdapter procureAdapter;
	/** 首页个人展示adapter **/
	private PersonGridAdapter personAdapter;
	/** 首页活动列表 adapter**/
	private ActivitiesListViewAdapter activitiesAdapter;
	
	/** 顶部banner **/
	private CirculatoryViewPager cvp_banner;
	/** 活动列表 **/
	private MyListView listview_activities;
	/** 搜附近-超星榜-热通告-星工厂  **/
	private MyGridView grid_procure;
	/** 个人展示列表 **/
	private MyGridView grid_person; 
	/** 搜索栏 **/
	private RelativeLayout rl_bar;
	/** 搜索栏 **/
	private RelativeLayout rl_search;
	/** 搜索图标 **/
	private ImageView img_search;
	/** 搜索提示 **/
	private TextView txt_search;
	/** 扫二维码 **/
	private LinearLayout linear_saoma;
	
	/** 消息 **/
	private LinearLayout linear_message;
	
	/** banner图片 **/
	private ArrayList<String> bannerPics;
	
	private ArrayList<HomeBanner> bannerData;
	/** 快捷功能数据-搜附近-超星榜-热通知-星工厂 **/
	private ArrayList<HomeShortcutMenu> adFocusImgList;
	/** 活动数据 **/
	private ArrayList<HomeBanner> activitiesList;
	/** 个人秀数据 **/
	private ArrayList<HomeStarShow> personImgList;
	
	private SharedPreferencesUtil mShPreferencesUtil;
	
	/**
	 * 标记是否在刷新
	 */
	private boolean isReflesh;
	
	/** 从首页进入扫描标记 */
	public final static int FROMHOME_TAG = 1;
	/** 扫一扫 **/
	private final static int BARCODE_REQUEST_CODE = 1;
	
	public static IndexFragment newInstance() {
		
		IndexFragment fragment = new IndexFragment();
		return fragment;
	}
	
	public static IndexFragment newInstance(int status) {
		
		Bundle args = new Bundle();
		args.putInt("", status);
		IndexFragment fragment = new IndexFragment();
		fragment.setArguments(args);
		return fragment;
	}
	@Override
	public void onAttach(Activity activity) {
		this.mActivity = activity;
		mShPreferencesUtil = new SharedPreferencesUtil(mActivity);
		super.onAttach(activity);
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		bannerPics = new ArrayList<String>();
		
		adFocusImgList = new ArrayList<HomeShortcutMenu>();
		activitiesList = new ArrayList<HomeBanner>();
		personImgList = new ArrayList<HomeStarShow>();
		
		bannerData = new ArrayList<HomeBanner>();
		
		procureAdapter = new ProcureGridAdapter(mActivity, adFocusImgList);
		
		activitiesAdapter = new ActivitiesListViewAdapter(mActivity, activitiesList);
		
		personAdapter = new PersonGridAdapter(mActivity, personImgList);
		
		ArrayList<HomeShortcutMenu> procures = new ArrayList<HomeShortcutMenu>();
		HomeShortcutMenu ad1 = new HomeShortcutMenu();
		ad1.setTitle("搜附近");
		ad1.setPic(R.drawable.icon_index_nearby);
		
		HomeShortcutMenu ad2 = new HomeShortcutMenu();
		ad2.setTitle("超星榜");
		ad2.setPic(R.drawable.icon_index_star);
		
		HomeShortcutMenu ad3 = new HomeShortcutMenu();
		ad3.setTitle("热通告");
		ad3.setPic(R.drawable.icon_index_hot);
		
		HomeShortcutMenu ad4 = new HomeShortcutMenu();
		ad4.setTitle("星工厂");
		ad4.setPic(R.drawable.icon_index_star_factory);	
		
		procures.add(ad1);
		procures.add(ad2);
		procures.add(ad3);
		procures.add(ad4);
		adFocusImgList.addAll(procures);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		// 开始轮播Banner
		cvp_banner.startCirculation();
	}
	
	@Override
	public void onPause() {
		super.onPause();
		// 停止轮播Banner
		cvp_banner.stopCirculation();
	}
	
	@Override
	public void onStop() {
		super.onStop();
	}
	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
		if (mView == null) {
			mView = inflater.inflate(R.layout.fragment_index, container, false);
			initView(mView);
		} else {
			ViewGroup parent = (ViewGroup) mView.getParent();
			if (parent != null) {
				parent.removeView(mView);
			}

			// 防止切换时，刷新动画不消失的BUG
			if (swipe_ly != null && swipe_ly.isRefreshing()) {
				swipe_ly.setRefreshing(false);
			}
		}
		setAttribute();
		return mView;
	}
	
	/**
	 * 初始化View
	 * @param view
	 */
	private void initView(View view){
		swipe_ly = (PullPushRefreshLayout)view.findViewById(R.id.swipe_ly);
		sv_procure = (ObservableScrollView)view.findViewById(R.id.sv_procure);
		cvp_banner = (CirculatoryViewPager)view.findViewById(R.id.cvp_banner);
		
		grid_procure = (MyGridView)view.findViewById(R.id.grid_procure);
		
		listview_activities = (MyListView)view.findViewById(R.id.listview_activities);
		
		grid_person = (MyGridView)view.findViewById(R.id.grid_person); 
		
		rl_bar = (RelativeLayout)view.findViewById(R.id.rl_bar);
		rl_search = (RelativeLayout) view.findViewById(R.id.rl_search);
		
		img_search = (ImageView) view.findViewById(R.id.img_search);
		txt_search = (TextView) view.findViewById(R.id.txt_search);
		linear_saoma = (LinearLayout) view.findViewById(R.id.linear_saoma);
		linear_message = (LinearLayout) view.findViewById(R.id.linear_message);
		
	}
	/** 广告视图的高度 **/
	private int adViewHeight;
	
	/** 搜索栏高度 **/
	private float rlBarHeight = 0f;
	/**
	 * 设置控件属性
	 */
	private void setAttribute(){
		// 控制banner大小
		//adViewHeight = (int) (DeviceUtil.getDeviceWidth(getActivity()) * 750 / 2116f);
		
		//LayoutParams bannerLp = cvp_banner.getLayoutParams();
		//bannerLp.height = adViewHeight;
		cvp_banner.setPageOnClick(bannerListener);
		// 搜索栏高度
		rlBarHeight = DeviceUtil.dip2px(mActivity, 48);
		swipe_ly.setProgressViewOffset(false, 0, (int) rlBarHeight);
		
		// 搜附近-超星榜-热通告-星工厂
		grid_procure.setAdapter(procureAdapter);
		grid_procure.setOnItemClickListener(onProcureItemClickListener);
		procureAdapter.notifyDataSetChanged();
		
		//活动列表
		listview_activities.setAdapter(activitiesAdapter);
		
		//个人展示
		grid_person.setAdapter(personAdapter);
		grid_person.setOnItemClickListener(procureLisenner);
		
		rl_search.setOnClickListener(this);
		linear_message.setOnClickListener(this);
		
		linear_saoma.setOnClickListener(this);
		
		swipe_ly.setOnRefreshListener(this);
		
		getIndexPageDataFromApi();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rl_search: //搜索
			SearchActivity.intoActivity(getActivity(), "", 0);
			break;
		case R.id.linear_message://进入我的消息
			//判断是否登录
			if (!mShPreferencesUtil.getLoginState()) {
                
                LoginActivity.intoActivity(mActivity,Constants.LOGIN_REQUEST_CODE,Constants.MAIN_MSG_TAB);
                
            }else{
            	
            	((MainActivity)mActivity).setMessageChecked();
            } 
			break;
		case R.id.linear_saoma:
			UmengAnalyticUtil.onEventTimes(getActivity(), "clickscancode");
			Intent intent = new Intent(getActivity(), CaptureActivity.class);
			intent.putExtra("FromTag", FROMHOME_TAG);
			startActivityForResult(intent, BARCODE_REQUEST_CODE);
			break;
		default:
			break;
		}
		
	}
	
	/**
	 * 搜附近-超星榜-热通告-星工厂
	 */
	private OnItemClickListener onProcureItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			
			switch (position) {
			case 0:
				SearchNearbyActivity.intoActivity(getActivity());
				break;
			case 1:
				Toast.makeText(getActivity(), "超星榜H5", Toast.LENGTH_SHORT).show();
				break;
			case 2:
				HotAnnunciateActivity.intoActivity(getActivity());
				break;
			case 3:
				Toast.makeText(getActivity(), "星工厂(详情H5)", Toast.LENGTH_SHORT).show();
				StarFactoryActivity.intoActivity(getActivity());
				break;

			}
			
		}
		
	};
	
	
	
	/**
	 * 个人秀点击到个人主页
	 */
	private OnItemClickListener procureLisenner = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			
			ToastUtil.show(mActivity, "选择："+position);
		}
		
	};
	
	/**
	 * 服务端获取首页数据
	 */
	private void getIndexPageDataFromApi() {

		if (!AndroidUtil.isNetworkAvailable(mActivity)) {
			ToastUtil.show(mActivity,getResources().getString(R.string.no_connector));
			return;
		}
		if(isReflesh){
			return ;
		}
		isReflesh = true;
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();

		Map<String, String> lastParams = NetworkUtil.generaterPostRequestParams(mActivity, params);

		String postUrl = HttpUrlConstant.getPostUrl(mActivity,HttpUrlConstant.INDEX_PAGE_DATA);
		OnResponseListener<HomePageDataResponse> listener = new OnResponseListener<HomePageDataResponse>(mActivity) {

			@Override
			public void onSuccess(HomePageDataResponse response) {

				Result result = response.getBody().getResult();
				ArrayList<HomeBanner> topbanner = result.getTopbanner();
				ArrayList<HomeBanner> conbanner = result.getConbanner();
				ArrayList<HomeStarShow> userlist = result.getUserlist();
				setTopBanners(topbanner);
				setConBanner(conbanner);
				setPersons(userlist);
			}

			@Override
			public void onError(String code, String message) {
				isReflesh = false;
				stopReflesh();
				ToastUtil.show(mActivity, message);
			}

			@Override
			public void onCompleted() {
				isReflesh = false;
				dismissProgress();
				stopReflesh();
			}
		};
		executeRequest(new FastJsonRequest<HomePageDataResponse>(
				Request.Method.POST, postUrl, HomePageDataResponse.class,
				listener, listener).setParams(lastParams));

	}

	@Override
	public void onRefresh() {
		// 判断网络是否连接
		if (!AndroidUtil.isNetworkAvailable(getActivity())) {
			Toast.makeText(getActivity(), R.string.no_connector, Toast.LENGTH_SHORT).show();
			if (swipe_ly != null) {
				swipe_ly.setRefreshing(false);
			}
			return;
		}
		getIndexPageDataFromApi();
	}
	
	/**
	 * banner点击事件
	 */
	private PageClickListenner bannerListener = new PageClickListenner() {

		@Override
		public void click(int position) {
			String url = bannerData.get(position).getBannerUrl();
			if (TextUtils.isEmpty(url)) {
				return;
			}
			/*Intent intent = new Intent(getActivity(), WebViewActivity.class);
			intent.putExtra("url", url);
			intent.putExtra("activityId", bannerList.get(position).getId());
			intent.putExtra("urlType", WebViewActivity.TYPE_ACTIVITY);
			startActivity(intent);*/
		}
	};
	
	
	
	/**
	 * ScrollView停止刷新 <br/>
	 */
	private void stopReflesh() {
		if (swipe_ly != null) {
			swipe_ly.setRefreshing(false);
		}
	}
	
	private void setTopBanners(ArrayList<HomeBanner> topbanner){
		bannerData.clear();
		bannerData.addAll(topbanner);
		setBannerDatas();
	}
	/**
	 * 设置首页banner的数据
	 */
	private void setBannerDatas() {
		if (bannerData.size() == 0) {
			cvp_banner.setVisibility(View.GONE);
			return;
		}
		if (cvp_banner.getVisibility() == View.GONE) {
			cvp_banner.setVisibility(View.VISIBLE);
		}
		bannerPics.clear();
		for (int i = 0; i < bannerData.size(); i++) {
			bannerPics.add(bannerData.get(i).getBannerUrl());
		}
		//设置图片
		cvp_banner.setData(bannerPics);
		//开始轮播
		cvp_banner.startCirculation();
	}
	
	private void setConBanner(ArrayList<HomeBanner> conbanner){
		activitiesList.clear();
		activitiesList.addAll(conbanner);
		activitiesAdapter.notifyDataSetChanged();
	}
	
	private void setPersons(ArrayList<HomeStarShow> userlist){
		personImgList.clear();
		personImgList.addAll(userlist);
		personAdapter.notifyDataSetChanged();
	}
	
	
}
